package org.ufinity.hsms.common.service;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import android.os.Handler;

public class ServerMonitorService extends Service
{

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	/*private TimerTask mTimerTask;
	private Timer mTimer;
	private int mTimerID = 0;
	private final String TAG = "ServerMonitorService";
	private Context context;
	public HostGroupCollection hgCollection;
	private NoRepeatRandomInt intGenerator;
	private MyBinder myBinder = new MyBinder();
	private NoticeCollection noticeCollection = new NoticeCollection();
	
	@Override
	public IBinder onBind(Intent intent) {
		return myBinder;
	}
	
	@Override
	
	 * 当服务第一次创建时 调用该方法
	
	public void onCreate()
	{
		//Toast.makeText(this, TAG + " Created", Toast.LENGTH_LONG).show();   
		android.util.Log.v(this.TAG, "onCreate");
		super.onCreate();
		
		this.context = this;
		this.mTimer = new Timer();
		this.hgCollection = new HostGroupCollection();
		this.intGenerator = new NoRepeatRandomInt(1, 100000);
	}
	
	@Override  
	public void onDestroy() {   
	        //Toast.makeText(this, TAG + " Stopped", Toast.LENGTH_LONG).show();   
	        Log.d(TAG, "onDestroy");    
	    }   
	       
	@Override  
	public void onStart(Intent intent, int startid) {   
	        //Toast.makeText(this, TAG + " Started", Toast.LENGTH_LONG).show();  
	        Log.d(TAG, "onStart");   
	        StartTimer();
	}   
	
	// Define handler
    public Handler handler = new Handler(){
    	
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            
            //Toast.makeText(context, String.valueOf(msg.what), Toast.LENGTH_LONG).show(); 
            // Get HostGroup and Hosts Info
            if (hgCollection.isEmpty())
            {
            	initiateHostGroup();
            	initiateHosts();
            	
            	showNotification("主机组和主机数量", 
            					 "主机组和主机数量", 
            					 "主机组数量:"+hgCollection.getHostGroupCount()+",主机数量:" + hgCollection.getHostCount(),
            					 R.drawable.noticeicon,
            					 R.drawable.noticeicon,
            					 context);
            }
            else
            {
            	List<HGTreeNode> list = hgCollection.getTreeNodeList();
            	
            	for (int i = 0; i < list.size(); i++)
            	{
            		List<HostEntity> hostList = list.get(i).childs;
            		
            		for (int j = 0; j < hostList.size(); j++)
            		{
            			HostEntity host = hostList.get(j);
            			CheckHost(host);
            		}
            	}
            }
        }
    };
	
    private void StartTimer()
    {
        this.mTimerTask = new TimerTask()
        {
            public void run() {
            	Log.i(TAG, Thread.currentThread().getName());
            	mTimerID ++;
            	
            	// 定义一个消息传过去
                Message msg = new Message();
                msg.what = mTimerID;
                //msg.arg1 =(int) (mTimerID);
                handler.sendMessage(msg);
            }          
        };
       
        mTimer.schedule(mTimerTask, 60000,60000);
    }
    
    
    
    private void CheckHost(HostEntity host)
    {
    	try
		{
			//long timeTill = System.currentTimeMillis() / 1000L;
			//long timeFrom = timeTill - 3600*24;
			//String lastChangeSince = String.valueOf(timeFrom);
			//String lastChangeTill = String.valueOf(timeTill);
	        //String result = ZabbixApiClient.getTriggersByHostId(host.HostId, lastChangeSince, lastChangeTill);
	        String result = ZabbixApiClient.getRecentTriggersByHostId(host.HostId);
	        //String result = ZabbixApiClient.getTriggersByHostId(host.HostId);
	        //android.util.Log.v("result", result);	        
	        JSONObject jsonObj = new JSONObject(result);
			
			if (jsonObj.has("result") 
				&& !jsonObj.getString("result").equals("[]"))
			{
				//JSONArray jsonArray = jsonObj.getJSONArray("result");
				
				//for (int i = 0; i < jsonArray.length(); i++) 
				//{   
	                //JSONObject item = jsonArray.getJSONObject(i);
				JSONObject item = new JSONObject(jsonObj.getString("result"));
                NoticeInfo notice = new NoticeInfo();
                notice.HostId = host.HostId;
                notice.HostName = host.HostName;
                notice.Description = item.getString("description");
                notice.LastClock = item.getString("lastchange");
                
                if (this.noticeCollection.existed(notice) == false)
                {
                	this.noticeCollection.addNotice(notice);
                	long happenedTime = Long.parseLong(notice.LastClock) * 1000L;
	                
	                showNotification(notice.Description, 
          					 notice.HostName, 
          					 notice.Description,
          					 intGenerator.next(),
          					 R.drawable.noticeicon,
          					 happenedTime,
          					 host.HostId,
          					 context);
                }
				//}
			}
			else
			{
				
				// SessionId is out of date
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
            	builder.setTitle("Session已过期，请重新登录");
            	builder.setPositiveButton(this.getResources().getString(R.string.sure), new DialogInterface.OnClickListener() {
 
    				@Override
    				public void onClick(DialogInterface dialog, int which) {
    					Intent intent = new Intent(HostStatusActivity.this, LoginActivity.class);
    					startActivity(intent);
    				}
    			});
            	builder.show();
            	
            	return;
            	
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
    }
    
    private String getGroupId(JSONArray arr )
	{
		String retValue = "";
		
		try
		{
			for (int i = 0; i < arr.length(); i++)
			{
				JSONObject item = arr.getJSONObject(i);
				retValue = item.getString("groupid");
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		return retValue;
	}
    
    private void initiateHosts()
	{
		try
		{
			String result = ZabbixApiClient.getHost();
			
			JSONObject hostObj = new JSONObject(result);
			
			if (hostObj.has("result"))
			{
				JSONArray jsonArray = hostObj.getJSONArray("result");
				
				for (int i = 0; i < jsonArray.length(); i++) 
				{   
	                JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象   
	                
	                JSONArray groupArray = item.getJSONArray("groups");
	                String groupid = getGroupId(groupArray);
	                
	                HostEntity hostEntity = new HostEntity();
	                hostEntity.HostId = item.getString("hostid");
	                hostEntity.HostName = item.getString("host");
	                hostEntity.IP = item.getString("ip");
	                
	                this.hgCollection.Add(groupid, hostEntity);
	            }   
			}
			else
			{
				// SessionId is out of date
				//String titleMessage = "超时，请重新登录";
				//Toast.makeText(context, titleMessage, Toast.LENGTH_LONG).show(); 
				SharedPreferences sharedPreferences = this.getSharedPreferences("remember", Activity.MODE_PRIVATE);
		    	String username = sharedPreferences.getString("username", "");
		    	String password = sharedPreferences.getString("password", "");
		    	
		    	String strResponse = ZabbixApiClient.getAuthInfo(username, password);
		    	
		    	try
		    	{
		    		JSONObject obj = new JSONObject(strResponse); 
					
		    		if (obj.has("result"))
		    		{
		    			result = obj.getString("result");
						ZabbixApiClient.SessionId = result;
		    		}
		    	}
		    	catch (Exception ex)
		    	{
		    		ex.printStackTrace();
		    	}
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
    
    private void initiateHostGroup()
	{
		try
		{
			String result = ZabbixApiClient.getHostGroup();
			
			JSONObject hgObj = new JSONObject(result);
			List<HGTreeNode> treeNodeList = this.hgCollection.getTreeNodeList();
			
			if (hgObj.has("result"))
			{
				JSONArray jsonArray = hgObj.getJSONArray("result");
				
				for (int i = 0; i < jsonArray.length(); i++) 
				{   
	                JSONObject item = jsonArray.getJSONObject(i);  
	                
	                HGTreeNode node = new HGTreeNode();
					node.parent = new HostGroupEntity();
	                node.parent.HostGroupId = item.getString("groupid");
	                node.parent.HostGroupName = item.getString("name");
	               
	                treeNodeList.add(node);
	            }   
			}
			else
			{
				//String titleMessage = "超时，请重新登录";
				//Toast.makeText(context, titleMessage, Toast.LENGTH_LONG).show(); 
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
    
	private void showNotification(String tickerText, 
            String contentTitle, 
            String contentText, 
            int id, 
            int resId,
            Context context)
	{
		NotificationManager noticeMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notice = new Notification(resId, tickerText, System.currentTimeMillis());
		
		notice.flags |=	Notification.FLAG_AUTO_CANCEL;	
		Intent intent= new Intent(context, HostsActivity.class);		
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
		//PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, LoginActivity.class), 0);
		notice.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		//notice.flags = Notification.FLAG_FOREGROUND_SERVICE;
		//startForeground(id, notice);
		
		//noticeMgr.notify(id, notice);
		noticeMgr.notify(5, notice);
	}
	
	private void showNotification(String tickerText, 
            String contentTitle, 
            String contentText, 
            int id, 
            int resId,
            long happenedTime,
            String hostId,
            Context context)
	{
		NotificationManager noticeMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notice = new Notification(resId, tickerText, happenedTime);
		
		notice.flags |=	Notification.FLAG_AUTO_CANCEL;	
		Intent intent= new Intent(context, HostsActivity.class);
		intent.putExtra("request", true);
		intent.putExtra("hostId", hostId);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 5, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		//PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, LoginActivity.class), 0);
		notice.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		//notice.flags = Notification.FLAG_FOREGROUND_SERVICE;
		//startForeground(id, notice);
		//noticeMgr.notify(id, notice);
	    
		noticeMgr.notify(5, notice);
	}
	
	public class MyBinder extends Binder
	{
		public ServerMonitorService getService()
		{
			return ServerMonitorService.this;
		}
	}*/
}
